package com.zja.servlet;


import com.zja.model.Article;
import com.zja.model.JsonResponse;
import com.zja.service.ArticleService;
import com.zja.service.Impl.ArticleServiceImpl;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

/**
 * @author JA
 * @date: 2025/5/4
 * description:获取文章列表（可选按知识库 ID 过滤）
 */
@WebServlet("/api/article/list")
public class ListArticlesServlet extends HttpServlet {
    private final ArticleService articleService = new ArticleServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        String kbIdStr = req.getParameter("knowledgeBaseId");
        List<Article> articles;

        try {
            if (kbIdStr != null) {
                Long kbId = Long.parseLong(kbIdStr);
                articles = articleService.getArticlesByKnowledgeBaseId(kbId);
            } else {
                articles = articleService.getAllArticles();
            }

            ServletUtil.writeJsonResponse(resp, JsonResponse.success("查询成功", articles));
        } catch (NumberFormatException e) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("知识库 ID 格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("获取文章列表失败"));
        }
    }
}
